package cn.wolfcode.luowowo.wensite.web.controller;

import cn.wolfcode.luowowo.wensite.util.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {

    @Value("${file.path}")
    private String basePath;

    //本地图片上传
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object uploadImg(MultipartFile pic) {
        //硬盘服务器 使用springboot的文件上传处理器
        String filename = UploadUtil.upload(pic, basePath);
        return filename;
    }

    //页面图片上传插件
    @RequestMapping("/uploadImg_ckj")
    @ResponseBody
    public Map<String, Object> upload(MultipartFile upload, String module) {
        HashMap<String, Object> map = new HashMap<>();
        String imagePath = null;
        if (upload != null && upload.getSize() > 0) {
            try {

                //图片保存,然后返回图片保存后的路径
                imagePath = UploadUtil.upload(upload, basePath);
                //表示保存成
                map.put("upload", 1);
                //然后拼接路径地址
                map.put("url", "/" + imagePath);
            } catch (Exception e) {
                e.printStackTrace();
                //表示保存失败
                map.put("upload", 0);
                //创建一个新的集合用来保存异常信息
                HashMap<String, Object> mm = new HashMap<>();
                //使用新集合保存异常信息
                mm.put("message", e.getMessage());
                //然后把保存异常信息的集合放进map集合中
                map.put("error", mm);
            }
        }
        return map;
    }
}
